package cn.net.isir.controller.miniprogram;

import cn.net.isir.common.*;
import cn.net.isir.entity.WxMinipUserinfo;
import cn.net.isir.service2.WxMinipPayNotifyService;
import cn.net.isir.service2.WxMinipUserinfoService;
import cn.net.isir.service2.WxminipPayService;
import cn.net.isir.utils.RequestUtils;
import cn.net.isir.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

//import com.sq.entity.Finance;
//import com.sq.entity.FinanceLog;

/**
 * @author liuxubo
 * @filename WxPayController.java
 * @package cn.net.isir.controller.miniprogram
 * @email lxb@isir.net.cn
 * @date 2018/09/18
 * @comment
 * @since 1.7
 */
@RestController("minipWxPayController")
@RequestMapping(value = "/minip/wxpay/")
public class WxPayController {

    private static Logger logger = Logger.getLogger(WxPayController.class);

    @Resource
    private WxminipPayService minipWxminipPayService;
    @Resource
    private WxMinipPayNotifyService wxMinipPayNotifyService;
    @Resource
    private WxMinipUserinfoService wxMinipUserinfoService;
//    @Resource
//    private FinanceService financeService;
//    @Resource
//    private FinanceLogService financeLogService;

    /**
     * 统一下单接口
     *
     * @param request 请求
     * @param obj     请求参数
     * @return 结果
     */
    @RequestMapping(method = RequestMethod.POST, value = "order")
    public ResultObject uniformOrder(HttpServletRequest request, @RequestBody RequestObject obj) {
        //声明返回值
        ResultObject ro;
        //声明参数解码后的储存变量
        Map<String, Object> reqParamMap = new HashMap<>();
        //需要检查的字段名
        String[] columns = new String[]{"unionid", "shopid", "orderid"};
        //检查失败则返回缺失的字段提示
        if ((ro = RequestUtils.parametersCheck(obj, reqParamMap, columns)).getResult() != 200) {
            return ro;
        }
        String client = String.valueOf(reqParamMap.get("client"));
        String unionid = String.valueOf(reqParamMap.get("unionid"));
        String shopid = String.valueOf(reqParamMap.get("shopid"));
        String orderid = String.valueOf(reqParamMap.get("orderid"));
//        if (CacheManager.getUserInfoByLoginStatus(unionid) == null) {
//            ro.setResult(500);
//            ro.setMessage("当前未绑定用户，请求失败");
//            return ro;
//        }
        WxMinipUserinfo userinfo = new WxMinipUserinfo();
        userinfo.setUnionid(unionid);
        userinfo = wxMinipUserinfoService.selectOne(userinfo);
        if (userinfo == null) {
            ro.setResult(500);
            ro.setMessage("未查询到unionid对应的用户，请求失败");
            return ro;
        }
        String clientIP = request.getRemoteAddr();

        if ("wx".equals(client)) {
            ro = minipWxminipPayService.uniformOrder(clientIP, unionid, shopid, orderid);
        }

        return ro;
    }

    /**
     * 微信支付结果通知
     *
     * @param request 请求
     * @return 返回结果
     */
    @RequestMapping(value = "notify")
    @ResponseBody
    public String notify(HttpServletRequest request) {
        try {
            //读取微信通知信息(从request输入流中，而非request.getParam...)
            InputStream inStream = request.getInputStream();
            int _buffer_size = 1024;
            String result = null;
            if (inStream != null) {
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] tempBytes = new byte[_buffer_size];
                int count;
                while ((count = inStream.read(tempBytes, 0, _buffer_size)) != -1) {
                    outStream.write(tempBytes, 0, count);
                }
                outStream.flush();
                //将流转换成字符串
                result = new String(outStream.toByteArray(), "UTF-8");
                logger.info("======================微信支付通知==============================");
                logger.info(result);
                logger.info("======================微信支付通知==============================");
                if (StringUtils.isBlank(result)) {
                    //如果失败返回错误，微信会再次发送支付信息
                    XML xml = XML.generateXML("xml");
                    xml.addChild("return_code", "FAIL");
                    xml.addChild("return_msg", "FAIL");
                    return xml.toConvertString();
                }
            }
            return wxMinipPayNotifyService.notify(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
            logger.info(e.getMessage());
            //如果失败返回错误，微信会再次发送支付信息
            XML xml = XML.generateXML("xml");
            xml.addChild("return_code", "FAIL");
            xml.addChild("return_msg", "FAIL");
            return xml.toConvertString();
        }
    }
}
